package cc.rico.tutorial.helloworld;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import cc.rico.tutorial.RabbitMQConnectionUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import lombok.extern.slf4j.Slf4j;

/**
 * @author rico 2017年6月26日
 *
 */
@Slf4j
public class Recv {
	private static final String QUEUE_NAME = "helloworld";
	
	public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
		Connection conn = RabbitMQConnectionUtil.getConnection();
		Channel channel = conn.createChannel();

		// String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		log.info("Waiting for message. To exit press Ctrl +C");
		
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
				String message = new String(body, "UTF-8");
				log.info("Received.message = {} ", message);
			}
		};

		// String queue, boolean autoAck, Consumer callback
		channel.basicConsume(QUEUE_NAME, true, consumer);

		Thread.sleep(1000 * 10);
		RabbitMQConnectionUtil.close(conn, channel);
	}
}
